package com.paic.mhis.hcpms.common.validator;

import java.text.MessageFormat;
import java.util.Map;

import com.paic.pafa.app.biz.bo.validation.DefaultValidStatus;
import com.paic.pafa.app.biz.bo.validation.ValidStatus;

public abstract class MapValueValidator extends MapValidator
{

	public MapValueValidator(Object key, String message, String code)
	{
		this.key = key;
		this.message = message;
		this.code = code;
	}

	protected Object key;
	protected final String message;
	protected final String code;

	protected ValidStatus checkMap(Map<Object, Object> fieldMap)
	{
		Object value = getValue(fieldMap);
		ValidStatus validStatus = new DefaultValidStatus();
		if(validateValueFailed(value))
		{
			validStatus.addError(new ErrorEntry(code, this.key, getMessage(value)));
		}
		return validStatus;
	}

	private Object getValue(Map<Object, Object> fieldMap)
	{
		if(!hasLevel(key))
		{
			return fieldMap.get(key);
		}
		String[] keys = ((String)key).split("\\.");
		
		String actualKey = keys[keys.length - 1];
		this.key = actualKey;
		
		return fieldMap.get(this.key);
	}

	private boolean hasLevel(Object key)
	{
		int i = ((String)key).indexOf(".");
		return i > 0;
	}

	protected boolean isEmpty(Object val)
	{
		if(null == val)
		{
			return true;
		}
		else if(!(val instanceof String))
		{
			return false;
		}
		else
		{
			return ((String)val).trim().equals("");
		}
	}
	
	private boolean validateValueFailed(Object val)
	{
		return !validateSuccess(val);
	}


	abstract protected boolean validateSuccess(Object value);

	/**
	 * <p>
	 * 格式化消息 xxx{1}yyy{2}
	 * </p>
	 * 
	 * @param val
	 * @return String
	 */
	protected String getMessage(Object val)
	{
		return MessageFormat.format(message, getArguments(val));
	}

	/**
	 * <p>
	 * 子类可覆盖，获取格式化消息的参数
	 * </p>
	 * 
	 * @param val
	 * @return Object[]
	 */
	protected Object[] getArguments(Object val)
	{
		return new Object[0];
	}

	public Object getKey()
	{
		return key;
	}

	public String getMessage()
	{
		return message;
	}

	public String getCode()
	{
		return code;
	}
}
